from django.forms import model_to_dict
from django.apps import apps

from backstage.models import *


def formatter(src, firstUpper=True):
    """
    将下划线分隔的名字,转换为驼峰模式
    :param src: test_date
    :param firstUpper: 转换后的首字母是否指定大写(  testDate or  TestDate)
    :return:testDate
    """
    arr = src.split('_')
    res = ''
    for i in arr:
        res = res + i[0].upper() + i[1:]

    if not firstUpper:
        res = res[0].lower() + res[1:]
    return res

# 通过二级分类id获取对应model
def secondtypeid_to_model(secondtypeid):
    table = MainDatacategory.objects.get(id=secondtypeid)
    table_name = model_to_dict(table)['tablename']
    # 将下划线命名变为驼峰，与model一致
    model_name = formatter(table_name)
    # 获取应用实例
    backstage = apps.get_app_config('backstage')
    DataModel = backstage.get_model(model_name)
    return DataModel

# 通过一级分类id获取对应model
def firsttypeid_to_model(firsttypeid):
    table = MainDatacategory.objects.get(id=firsttypeid)
    table_name = model_to_dict(table)['tablename']
    # 将下划线命名变为驼峰，与model一致
    model_name = formatter(table_name)
    # 获取应用实例
    backstage = apps.get_app_config('backstage')
    DataModel = backstage.get_model(model_name)
    return DataModel


# 删除评分，时间，屏蔽状态，等非内容元素
def del_redundant_element(DataModel, obj_list):
    keys = DataModel._meta.fields
    # 将所有的属性形成列表
    keys_list = [keys[i].name for i in range(len(keys))]
    # 列出不需要的属性
    remove_keys = ['userlabel', 'byobject', 'bycontent', 'viewcount', 'collectcount',
                   'commentcount', 'likecount', 'blockingstate', 'recommendedscores', 'modifiedtime', ]
    for obj in obj_list:
        for remove_key in remove_keys:
            try:
                obj.pop(remove_key)
            except:
                pass

    return obj_list
